package zb.service.imp;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import zb.pojo.Order;
import zb.pojo.User;
import zb.service.Userservice;

import javax.annotation.Resource;
import java.util.List;

@Service
public class Userserviceimp implements Userservice {
    @Resource
    RestTemplate restTemplate;
    @Resource
    DiscoveryClient discoveryClient;
    @Override
    public User findUserById(Integer uid) {
        User user=new User();
        user.setId(uid);
        user.setName("小明");
//        //远程调用
//        List orders=
//                restTemplate.getForObject("http://localhost:8081/showUserOrder/"+uid,List.class);
//        user.setOrders(orders);
//        return user;
        //根据注册在注册中心的服务名，获取十里集合
        List<ServiceInstance> instances = discoveryClient.getInstances("order-consul-server");
        //返回一个实例信息
        ServiceInstance serviceInstance=instances.get(0);
        //拼地址，动态获取端口
        String url=
                "http://"+serviceInstance.getHost()+":"
                +serviceInstance.getPort()+"/showUserOrder/"+uid;
        //远程调用
        List orders = restTemplate.getForObject(url, List.class);
        user.setOrders(orders);
        return user;

    }

    @Override
    public Integer UserAddOrder(Order order) {
       //远程调用
        Integer num=
                restTemplate.postForObject("http://localhost:8081/saveOrder",order,Integer.class);
        return num;
    }

    @Override
    public Integer UserDelOrder(Integer id) {
        Integer num=
                restTemplate.postForObject("http://localhost:8081/delOrder",id,Integer.class);
        return num;
    }

    @Override
    public Integer UserUpdateOrder(Order order) {
        Integer num=
                restTemplate.postForObject("http://localhost:8081/updateOrder",order,Integer.class);
        return num;
    }
}
